﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using System.Text;
using System.IO;
using Visiblox.Charts;

namespace onPulse01
{

    public partial class MainPage : PhoneApplicationPage
    {
        GoogleConnect connect = new GoogleConnect();
        GoogleData data = new GoogleData();
        private static List<BloodPresureRecord> allResults = new List<BloodPresureRecord>();
        public static ResultsDelegate resultsDelegate = new ResultsDelegate();
        private static bool refresh = true;
        public MainPage()
        {
            InitializeComponent();
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            Results.DataContext = resultsDelegate;
        }

        //load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
            connectAndGetResults();
        }

        //connect with Google Health and get results
        private void connectAndGetResults()
        {
            connect.GetResults();
            connect.getEvent += new GoogleGetHandler(connect_getEvent);
        }

        //set results values 
        private void connect_getEvent(object sender, GoogleGetEventArgs e)
        {
            if (refresh)
            {
                resultsDelegate.Results = allResults = data.getBloodPresureResults(e.Data);
                refresh = false;
            }
            
            //dane do wykresu
            bool systolic = false;
            chart.Series.Clear();
            for (int i = 0; i < 2; i++)
            {
                LineSeries lineSeries = new LineSeries();
                lineSeries.DataSeries = getChartLine(resultsDelegate.Results, systolic);
                lineSeries.LineStrokeThickness = 2;
                chart.Series.Add(lineSeries);
                systolic = true;
            }
        }
        #region Filtrowanie
        public static List<BloodPresureRecord> filterDataByDiastolic(int lower, int higher)
        {
            List<BloodPresureRecord> temp = new List<BloodPresureRecord>();
            foreach (BloodPresureRecord bpr in allResults)
            {
                if (bpr.Diastolic >= lower && bpr.Diastolic <= higher)
                    temp.Add(bpr);
            }
            return temp;
        }

        public static List<BloodPresureRecord> filterDataBSystolic(int lower, int higher)
        {
            List<BloodPresureRecord> temp = new List<BloodPresureRecord>();
            foreach (BloodPresureRecord bpr in allResults)
            {
                if (bpr.Systolic >= lower && bpr.Systolic <= higher)
                    temp.Add(bpr);
            }
            return temp;
        }

        public static List<BloodPresureRecord> filterDataByCount(int limit)
        {
            int Limit = allResults.Count;
            if(Limit > limit) Limit = limit;
            List<BloodPresureRecord> temp = new List<BloodPresureRecord>();
            for(int i = 0; i < Limit; i++)
            {
                temp.Add(allResults[i]);
            }
            return temp;
        }

        #endregion
        private DataSeries<DateTime, int> getChartLine(List<BloodPresureRecord> data, bool systolic)
        {
            DataSeries<DateTime, int> series = new DataSeries<DateTime,int>();
            foreach (BloodPresureRecord b in data)
            {
                if (systolic)
                    series.Add(new DataPoint<DateTime, int>(b.ExactDateTime, b.Systolic));
                else
                    series.Add(new DataPoint<DateTime, int>(b.ExactDateTime, b.Diastolic));
            }
            return series;
        }

        //go to Settings
        private void settings_click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/Settings/Settings.xaml", UriKind.Relative));
        }

        //refresh and update results
        private void refresh_click(object sender, EventArgs e)
        {
            connectAndGetResults();
        }
         
        //show datepicker in add new test result view
        private void showDatepicker(object sender, RoutedEventArgs e)
        {
            date.Visibility = Visibility.Collapsed;
            change_date.Visibility = Visibility.Visible;
        }

        //add and post new test result
        private void addNewResult(object sender, RoutedEventArgs e)
        {
            int systolic = 0;
            bool parse = Int32.TryParse(Systolic_Value.Text, out systolic);

            if (!parse || systolic < 10 || systolic > 500)
            {
                MessageBox.Show("Błędna wartość ciśnienia skurczowego.");
                return;
            }

            int diastolic = 0;
            parse = Int32.TryParse(Diastolic_Value.Text, out diastolic);

            if (!parse || diastolic < 10 || diastolic > 500)
            {
                MessageBox.Show("Błędna wartość ciśnienia rozkurczowego.");
                return;
            }

            string when = "";
            if (date.Visibility == Visibility.Visible)
                when = DateTime.Now.ToString("yyyy-MM-dd");
            else
                when = ((DateTime)NewDate.Value).ToString("yyyy-MM-dd");

            //post new results
            connect.PostBloodPresure(systolic, diastolic, when);
            connect.postEvent+= new GooglePostHandler(connect_postEvent);

        }

        //set results values 
        private void connect_postEvent(object sender, GooglePostEventArgs e)
        {
            string response = e.Data;

            if (response.Contains("Result: " + Systolic_Value.Text + "/" + Diastolic_Value.Text))
            {                
                connectAndGetResults();
                PanoramaView.DefaultItem = PanoramaView.Items[0];
                MessageBox.Show("Nowy pomiar został pomyślnie dodany.");                
            }
            else
            {
                MessageBox.Show("Wystąpił problem z dodaniem pomiaru. Spróbuj ponownie.");
            }
        }

        //set date in add new test result view
        private void setDate_onLoad(object sender, RoutedEventArgs e)
        {
            DateTime date = DateTime.Now;
            DayAndMonth_Static.Text = date.ToString("d MMMM");
            Year_Static.Text = date.Year.ToString();
        }

        private void filterBarIconButton_Click(object sender, System.EventArgs e)
        {
        	this.NavigationService.Navigate(new Uri("/Filter.xaml", UriKind.Relative));
        }
    }
}